import gtk
import re   # Regex lib

class WindowTemplate(gtk.Window):
    '''This is an "abstract" class that all GUI windows must implement'''
    def __init__(self,controller):
        ''''''
        gtk.Window.__init__(self,type=gtk.WINDOW_TOPLEVEL)
        self.controller = controller    # a reference to the main controller
        
        #shortcuts :
        self.locations = self.controller.locations
        self.shares = self.controller.shares
        self.config = self.controller.config
    
        self.validator = None
        
        self.set_icon_from_file(self.config.path['IMAGES']+'ico.png')
        
        self.accel_group = gtk.AccelGroup()
        self.accel_group.connect_group(gtk.keysyms.Escape,0, gtk.ACCEL_VISIBLE, self.delete_by_accel_callback)
        self.add_accel_group(self.accel_group)
        
        self.controller.windows.append(self)
        
        self.connect("delete-event",self.delete_event_callback)

    ### Shortcut ? inclure la classe validators dans windows template ?
    def add_validator(self,tb, regex, allow_empty):
        '''add a validator to validators'''
        if not self.validator:  # avoid to instantiate validators if there is no need
            self.validator = Validators(self.config)
        self.validator.add_validator(tb, regex, allow_empty)
    
    def remove_validator(self,tb):
        '''remove a validator from validators'''
        self.validator.remove_validator(tb)
    
    def enable_validator(self,tb):
        '''enable a validator effect'''
        self.validator.enable_validator(tb)        
    
    def disable_validator(self,tb):
        '''disable a validator effect'''
        self.validator.disable_validator(tb)
            
    def is_valid(self):
        '''check if validators are all valid'''
        return self.validator.is_valid()
    ###
    
    def build_hbox(self,widgets,homogeneous=True,spacing=5,expand=True,fill=True,padding=0):
        """
        Goal : Pack the gived widgets into an Horizontal Box
        Input : N-tuple of widgets
        Outout : Horizontal Box
        """
        hbox = gtk.HBox(homogeneous,spacing)
        for widget in widgets:
            hbox.pack_start(widget,expand,fill,padding)
        return hbox
        
    def build_vbox(self,widgets,homogeneous=True,spacing=5,expand=True,fill=True,padding=0):
        """ 
        Goal : Pack the gived widgets into an Vertical Box
        Input = N-tuple of widgets
        Outout = Vertical Box 
        """
        vbox = gtk.VBox(homogeneous,spacing)
        for widget in widgets:
            vbox.pack_start(widget,expand,fill,padding)
        return vbox
    
    def delete_by_accel_callback(self,accel_group,window,key,modifier):
        self.close()
    
    def delete_event_callback(self,*args):
        self.close()
    
    def close(self,*args):
        if self.__class__.__name__ == 'MainWindow':
            for window in [ window for window in self.controller.windows if window.__class__.__name__ != 'MainWindow']:
                    window.close()
        self.controller.windows.remove(self)
        self.destroy()
        
class Validators:
    '''this call is a container for validator witch provide add/remove/enable/disable validators and check if all are valid for form submitings'''
    def __init__(self,config):
        self.regex = config.regex
        self.validators = {}    #validators container
        ### --> goto config
        self.COLOR_WRONG = '#FFECCE'
        self.COLOR_VALID = '#FFFFFF'
        ###
        
    def add_validator(self,tb,regex,allow_empty=True):
        '''add a validator to a gtk.Entry, with the gived Rexex validation'''
        if regex in self.regex.store:   #<-- eviter d'utiliser directement store.
            regex = self.regex[regex]
        self.validators[tb] = Validator(self,tb,regex,allow_empty)
        tb.connect('changed', self.validators[tb].is_valid) #connect the gtk.Entry with his validator
        self.validators[tb].is_valid()
    
    def remove_validator(self,tb):
        '''remove a validator from a gtk.Entry'''
        del self.validators[tb]
    
    def enable_validator(self,tb):
        '''enable validation for the gived gtk.Entry'''
        self.validators[tb].enabled = True        
        self.validators[tb].is_valid()
        
    def disable_validator(self,tb):
        '''disable validation for the gived gtk.Entry'''
        self.validators[tb].enabled = False
        self.validators[tb].is_valid()
        
    def is_valid(self):
        '''check if all validator are ok'''
        for key,validator in self.validators.iteritems():
            if not validator.valid:
                return False
        return True
            
class Validator:
    '''Validator check if a gtk.Entry is valid according to the gived Regex'''
    def __init__(self,validators,tb,regex,allow_empty):
        self.validators = validators    # only for colosr, will be replaced by controler config
        self.tb = tb                    # the gtk.Entry witch it is linked
        self.regex = regex              # the regex to valid the text
        self.allow_empty = allow_empty  # if True allow to be empty
        self.valid = False              # True if the tb text match the regex
        self.enabled = True             # if False valid is always True
    
    def is_valid(self,*args):
        '''check if the tb text match the regex and set the tb background color'''
        if self.enabled == False or re.match(self.regex,self.tb.get_text()) or ( len(self.tb.get_text()) == 0 and self.allow_empty ):
            self.valid = True
            self.tb.modify_base(gtk.STATE_NORMAL,gtk.gdk.color_parse(self.validators.COLOR_VALID))
        else:
            self.valid = False
            self.tb.modify_base(gtk.STATE_NORMAL,gtk.gdk.color_parse(self.validators.COLOR_WRONG))